<template>
  <!--协同审批【在办箱】-->
  <div class="todo-box h-full bg-white wrapper-md">
    <BtnWidgets
      class="m-b"
      v-if="widgets.length"
      ref="btnWidget"
      :widgets="widgets"
      :widget-id="customWidgetId"
      @btn-click="handleBtnClick"
      @btn-select="handleValueChange"
      @query="onSearch"
    />
    <div style="height:93%" ref="modal" class="table-wrapper m-t-xs f14">
      <a-modal
        :destroyOnClose=true
        :dialog-style="{ top: '40px' }"
        :maskClosable= false
        :visible="visible"
        :title="modelTitle"
        okText='确认'
        cancel-text="取消"
        @cancel="handleCancel"
        @ok="handleOk"
        :bodyStyle="{'height':'700px'}"
        :width="1000"
      >
        <div class="row h-full businessItemMaterial">
          <a-row class="m-b-md">
            <a-col :span="3" class="text-align-right">
              <label class="m-r-lg">事项名称</label>
            </a-col>
            <a-col :span="8">
              <a-select class="w-full"
                        placeholder="请选择事项">
                <a-select-option v-for="item in this.businessItemMapList"
                                 @click="handClick(item)"
                                 :key="item.id"
                                 :value="item.id">{{item.item_name}}</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="3" class="text-align-right">
              <label class="m-r-lg">事项编码</label>
            </a-col>
            <a-col :span="8">
              <a-input :disabled=true
                       :value="this.selectedBusinessItem.item_code"/>

            </a-col>
          </a-row>
          <div class="attachment-info">
            <a-row class="m-b-md">
              <a-col :span="3" class="text-align-right">
                <label class="m-r-lg">记录类型</label>
              </a-col>
              <a-col :span="8">
                <a-select class="w-full"
                          placeholder="请选择事项">
                  <a-select-option v-for="item in this.selectedRecordType"
                                   :key="item.id"
                                   :value="item.value">{{item.name}}</a-select-option>
                </a-select>

              </a-col>
              <a-col :span="3" class="text-align-right">
                <label class="m-r-lg">事件类型</label>
              </a-col>
              <a-col :span="8">
                <a-select class="w-full"
                          placeholder="请选择事项">
                  <a-select-option v-for="item in this.selectedEventType"
                                   :key="item.id"
                                   :value="item.value">{{item.name}}</a-select-option>
                </a-select>

              </a-col>
            </a-row>
          </div>
          <a-row style="height: 90%; margin-top: 20px">
            <a-col class="border h-full" :span="24">
              <a-tree
                :checkable=true
                v-model="checkedKeys"
                :replaceFields="{ key:'id'}"
                :class="'h-full overflow-y-auto overflow-x-hidden'"
                :selected-keys="selectedKeys"
                :tree-data="businessMaterial"
                :load-data="onLoadMaterial"
                @check="onCheck"
              >
              </a-tree>
            </a-col>
<!--            <a-col class="border h-full text-align-center" :span="2">-->
<!--              <div class="btn-group">-->
<!--                <div>-->
<!--                  <a-button @click="addToList">添加</a-button>-->
<!--                </div>-->
<!--              </div>-->
<!--            </a-col>-->
<!--            <a-col class="border h-full" :span="12">-->
<!--              <a-list bordered :data-source="dataList">-->
<!--                <a-list-item slot="renderItem" slot-scope="item, index">-->
<!--                  {{ item.MaterialDataIDs.name }}&nbsp;&nbsp;&nbsp;-->
<!--                  ==>&nbsp;&nbsp;&nbsp; {{item.eventTypeDataIDs.name}}&nbsp;&nbsp;&nbsp;-->
<!--                  ==>&nbsp;&nbsp;&nbsp; {{item.recordTypeDataIDs.name}}-->
<!--                  <a-button class="m-l-md  pull-right"  type="link" @click="deleteSelectedItem(item,index)">-->
<!--                    删除-->
<!--                  </a-button>-->
<!--                </a-list-item>-->
<!--              </a-list>-->
<!--            </a-col>-->
          </a-row>
        </div>
      </a-modal>
      <div class="action-area">
        <div class="button">
          <a-button id="new" type="primary" @click="showModal">
            新建
          </a-button>
          <a-button id="refresh" type="primary" @click="onSearch">
            刷新
          </a-button>
        </div>
        <BtnWidgets
          v-if="widgets.length"
          ref="btnWidget"
          :widgets="widgets"
          :widget-id="customWidgetId"
          @btn-click="handleBtnClick"
          @btn-select="handleValueChange"
          @query="onSearch"
        />
      </div>
      <a-table
        class="dist-box-table"
        bordered
        :rowClassName="setRowClassName"
        :customRow="customRow"
        :loading="table.loading"
        :rowKey="(record, index)=>index"
        :columns="table.columns"
        :data-source="table.dataSource"
        :pagination="table.pagination"
        :scroll="{ x: false, y: table.dataSource.length>10?545:false }"
      >
         <span slot="operate" slot-scope="text,record">
<!--            <a-button  type="default" @click="updateItem(record)">-->
           <!--             编辑-->
           <!--           </a-button>-->
           <a-button class="m-l-md" type="danger" @click="deleteItem(record)">
             删除
           </a-button>
        </span>
      </a-table>
    </div>
  </div>
</template>

<script>
import BtnWidgets from '@c/Button/BtnWidgets'
import PageInitFn from '@/api/pageInitFn'
import projectService from '@/api/projectService'
import duban from '@/assets/img/duban.svg?inline'
import dapProjectService from "@/api/dapProjectService";
import businessService from "@/api/businessService";
import dicService from "@/api/dicService";
export default {
  name: 'businessItem',
  data() {
    return {
      duban,
      customWidgetId: '',
      collectRateNum: 1,
      widgets: [],
      filter: {
        businessFilter: this.$route.meta.matterType,
        businessNickFilter: null,
        filterText: '',
        pageIndex: 1,
        pageSize: 10
      },
      businessNickFilter: null,
      table: {
        columns: [],
        dataSource: [],
        loading: false,
        rowSelection: {
          selectedRowKeys: [],
          selectedRows: [],
          onChange: (selectedRowKeys, selectedRows) => {
            this.table.rowSelection.selectedRowKeys = selectedRowKeys
            this.table.rowSelection.selectedRows = selectedRows
          }
        },
        pagination: {
          pageSize: 10, // 默认每页显示数量
          total: 0,
          current: 1,
          showSizeChanger: true, // 显示可改变每页数量
          pageSizeOptions: ['10', '20', '50', '100', '200', '500'], // 每页数量选项
          showTotal: (total) => `共${total}条数据`, // 显示总数
          onShowSizeChange: (current, pageSize) => {
            this.filter.pageIndex = 1
            this.filter.pageSize = pageSize
            this.loadData(this.filterText)
          },
          onChange: (current, pageSize) => {
            this.filter.pageIndex = current
            this.filter.pageSize = pageSize
            this.table.pagination.current = current
            this.loadData(this.filterText)
          }
        }
      },
      rowId: '',
      visible: false,
      //模态对话框标题
      modelTitle: '请填写表单',
      businessItemMapList: null,
      businessMaterial: null,
      selectedBusinessItem: {},
      dataList: [],
      selectedMaterialDetail: [],
      selectedEventType: [],
      selectedRecordType:[],
      eventTypeDataIDs: [],
      MaterialDataIDs: [],
      recordTypeDataIDs:[],
      selectedKeys:[],
      checkedKeys:[]
    }
  },
  components: {
    BtnWidgets
  },
  methods: {
    onCheck(checkedKeys, info) {
      console.log('onCheck', checkedKeys, info);
      // todo 推送材料保存请求数据装配
      this.selectedKeys = info.checkedNodes;
    },
    getRecordType(){
        dicService.treeDicItemByDicName('流程任务完成监听记录类型').then((d) =>{
          console.log(d)
          this.selectedRecordType = d

      })

    },
    getEventType(){
        dicService.treeDicItemByDicName('环节事件类型').then((d) => {
        this.selectedEventType = d;
      });

    },
    deleteSelectedItem(item,index){
      this.dataList.splice(index,1)
      this.MaterialDataIDs.splice(index,1)
      this.eventTypeDataIDs.splice(index,1)
    },
    addToList() {
      if (this.selectedMaterialDetail.length === 0) {
        this.$message.error("请选择正确的字段")
      }
      else {
        this.dataList.push({
          MaterialDataIDs: this.selectedMaterialDetail,
          eventTypeDataIDs: this.selectedEventType,
          recordTypeDataIDs: this.selectedRecordType
        })
      }

    },
    async onLoadMaterial(treeNode) {
      if (!treeNode.value) return
      let businessMaterial = await businessService.getBusinessMaterialDetail(treeNode.value)
      console.log(businessMaterial)
      businessMaterial.children.forEach(item => {
        item.children = []
        item.title = item.name
        item.isLeaf = true

      })
      treeNode.dataRef.children = businessMaterial.children
      this.businessMaterial = [...this.businessMaterial];
    },
    pickMaterialDetail(keys, event) {
      console.log(keys, event)
      // console.log('pick---id>', id )
      // console.log('pick---event>', event)
      // if (event.selected){
      //   if (event.node._props.dataRef.name) {
      //     this.selectedMaterialDetail = event.node._props.dataRef
      //   }
      // } else {
      //   this.selectedMaterialDetail = [];
      // }


    },

    async handClick(item) {
      this.selectedBusinessItem = item;
      await this.getBusinessMaterialById(this.selectedBusinessItem.businessId);
    },

    getBusinessMaterialById(businessId) {
      console.log(businessId)
      return businessService.getBusinessMaterialById(businessId).then((d) => {
        console.log('获取到的材料目录列表======》', d)
        this.businessMaterial = d;
        this.businessMaterial.forEach(item => {
          item.title = item.categoryDTO.name
          item.value = item.categoryId
          item.isLeaf = false
        })
      })
    },

    getBusinessItemMapList() {
      dapProjectService.getBusinessItemMapList().then((d) => {
        console.log('获取业务事项列表--------》', d);
        this.loadOptions(d);
      })
    },
    loadOptions(d) {
      this.businessItemMapList = d;
      this.businessItemMapList.forEach(item => {
        item.value = item.id
        item.title = item.item_name
      })
    },
    onSearch(filterText) {
      this.filter.pageIndex = 1
      filterText.isTrusted ? this.loadData() : this.loadData(filterText)
    },
    setRowClassName(record, index) {
      return this.pageInitFn.setRowClassName(record)
    },
    handleBtnClick(btn) {
      this.pageInitFn.handleBtnClick(btn)
    },
    handleValueChange(value) {
      this.businessNickFilter = value.businessNickName || value.undefined
      this.loadData(this.filterText)
    },
    customRow(record, index, key) {
      record.key = key
      return this.pageInitFn.customRow(record, index)
    },
    async loadData(filterText = null) {
      console.log(this.$route.meta)
      this.filterText = filterText || null
      await this.pageInitFn.loadData({
        queryFilter: filterText || undefined,
        businessFilter: this.$route.meta.matterType,
        businessNickFilter: this.businessNickFilter,
        userId: this.userInfo.id
      })
    },
    projectCollect(record) {
      const _params = {
        projectId: record.projectId,
        collect: record.collect
      }
      projectService.projectCollect(_params).then((res) => {
        this.loadData()
        this.Event.$on('_REFRESH_TODO_BOX_', this.loadData)
      })
    },
    filterDicState(value, Dic) {
      if (!value) return ''
      for (const item of Dic) {
        if (item.value == value) {
          return item.name
        }
      }
    },
    showModal() {
      this.visible = true;
    },
    //关闭模态框
    handleCancel() {
      this.resetForm();
      this.visible = false;
    },
    //点击确认
    handleOk: async function () {
      const dataTemp = this.dataList;
      console.log('已选项参数值--------》', dataTemp)
      let value = {
        businessItemMapId: this.selectedBusinessItem.id,
        businessId:this.selectedBusinessItem.businessId,
        itemCode:this.selectedBusinessItem.item_code,
        recordType:'xxxx',
        eventType:'xxxx'
      };
      const itemList = [];
      dataTemp.forEach(item => {
        itemList.push({
          materialDirectoryId:item.MaterialDataIDs,
          materialDirectoryName:'xxxx',
          materialCategoryId:item.MaterialDataIDs.categoryId,
          materialCategoryName:'xxxx'
        })
      })
      const params = Object.assign(value,{itemList:itemList});
      console.log('装配后的参数------》', JSON.stringify(params))
      // await dapProjectService.saveBusinessItemMaterialList(params).then((d) => {
      //   console.log(d);
      // })
      this.resetForm();
      await this.loadData()
      this.visible = false;
    },
    resetForm(){
      this.selectedBusinessItem = {};
      this.dataList =[];
      this.businessMaterial = [];
    },

    // 编辑
    updateItem: function(record){
      this.visible = true;
      this.selectedBusinessItem = record
      console.log('点击编辑后的传入参数------------》', record)
      // this.$nextTick(() => {
      //   setTimeout(() => {
      //     this.form.setFieldsValue({
      //       item_code: record.F_ITEM_CODE,
      //       is_required: record.F_IS_REQUIRED,
      //       mate_sort_uuid: record.F_MATE_SORT_UUID,
      //       material_name: record.F_MATERIAL_NAME,
      //       material_type: record.F_MATERIAL_TYPE,
      //       material_uuid: record.F_MATERIAL_UUID
      //     })
      //   })
      // })
    },

    //删除
    deleteItem: function (record) {
      this.$confirm({
        title: '提示',
        content: '确认执行删除操作，删除后项目不可恢复！',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          dapProjectService.deleteBusinessItemMaterial({id : record.ID}).then((d) => {
            this.loadData()
          })
        }
      })

    }
  },
  watch: {
    checkedKeys(val) {
      console.log('onCheck', val);
    },
  },
  created() {
    this.pageInitFn = new PageInitFn(this)
    this.pageInitFn.created()
  },
  async mounted() {
    await this.pageInitFn.mounted()
    this.Event.$on('_REFRESH_TODO_BOX_', this.loadData)
    this.getBusinessItemMapList();
    this.getRecordType();
    this.getEventType();

  }


}
</script>

<style lang="less" scoped>
.overflow-y-auto {
  overflow-y: auto;
}

.overflow-x-hidden {
  overflow-x: hidden;
}

.businessItemMaterial {
  .btn-group {
    top: 45%;
    position: relative
  }
}

/deep/ .ant-input-group-wrapper {
  width: 300px;
}

/deep/ .ant-input-search-button {
  margin-right: 0;
}

.duban {
  margin-right: 5px;
  margin-left: -5px;
  cursor: pointer;
}

/deep/ .ant-pagination-total-text {
  float: left;
}

/deep/ .ant-table-pagination {
  width: 100%;
  text-align: right;
  align-self: flex-end;
}

#new {
  margin: 10px 10px 10px 0
}

#delete {
  margin: 10px 10px 10px 10px
}
.action-area{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
